define(["tool", "request"], function(login_tool, request) {
	var loginObj = {};
	//登录入口
	loginObj.OnLogin = function(username, password, successFun) {
		var wt = plus.nativeUI.showWaiting("登录中，请稍等...", {
			back: "none"
		});
		var mask = mui.createMask();
		mask.show(); //显示遮罩	
		now = login_tool.get_utc();
		request.requestAjax("post", "loginex", {
			username: username,
			password: password,
			time: now.toString()
		}, function(res) {
			wt.close();
			mask.close();
			console.log(JSON.stringify(res))
			if(res.state == true) {
				loginObj.OnSaveAccessToken(res.data.token);
				successFun(res.data);
			} else {
				mui.toast(res.error)
			}
		}, function(res) {
			wt.close();
			mask.close();
			mui.toast("网络错误,请检查网络连接")
			console.log(JSON.stringify(res))
			//alert("网络错误")
		})
	}

	//是否有accessToken存在
	loginObj.OnAccessToken = function OnAccessToken(call_success,call_error) {
		var obj = myStorage.getItem("accesstoken")
		var now = login_tool.get_utc()
		if(obj == null || obj.expire_time < now) { //已经过期了
			myStorage.removeItem("accesstoken")
			console.log(JSON.stringify(obj))
			call_error()
		} else if(obj.expire_time - now < 2 * 60 * 60) { //已经小于2个小时了，更新accesstoken
			request.requestAjax("post", "refresh_token", {
				refresh_token: obj.refresh_token
			}, function(res) {
				if(res.state == true) {
					loginObj.OnSaveAccessToken(res.data);
					call_success(res.data)
				} else {
					mui.toast(res.error)
					call_error()
				}
			}, function(res) {
				console.log(JSON.stringify(res))
				mui.toast("网络错误")
				call_error()
			},5000);
		} else { //验证accesstoken
			request.requestAjax("post", "check_token", {
				token: obj.access_token
			}, function(res) {
				console.log(JSON.stringify(res))
				if(res.state == true) {
					call_success(res.data)
				} else {
					mui.toast(res.error)
					call_error()
				}
			}, function(res) {
				console.log(res.responseText)
				console.log(JSON.stringify(res))
				mui.toast("网络错误")
				call_error()
			},5000);
		}
	}

	loginObj.OnSaveAccessToken = function(obj) {
		now = login_tool.get_utc();
		var expire_time = now + parseInt(obj.expire_time)
		obj.expire_time = expire_time;
		console.log(JSON.stringify(obj))
		myStorage.setItem("accesstoken", obj);
	}

	//第三方登录登录入口
	loginObj.OnThirdLogin = function(req_login, successFun, errorFun) {
		now = login_tool.get_utc();
		request.OnAjax("post", "third_login", req_login, function(data) {
			loginObj.OnSaveAccessToken(data);
			successFun();
		}, function(code) {
			if(code == 1085) {
				errorFun();
			}
		})
	}
	
	//第三方登录登录入口
	loginObj.OnCnagePwd = function(username, password, successFun) {
		var wt = plus.nativeUI.showWaiting(null, {
			back: "none"
		});
		now = login_tool.get_utc();
		request.OnAjax("post", "change_pwdex", {
			username: username,
			password: password
		}, function(data) {
			wt.close();
			successFun();
		}, function(code) {
			wt.close();
		})
	}

	return loginObj;
})